#!/usr/bin/perl

#############################################################################
# File: loadLibrary.pl
#
# Soderlund Lab, University of Arizona, 2010
#
# Load a TCW library. 
#
#############################################################################


# Maximum memory to use, in megabytes.
# A higher value may be necessary for very large projects.
my $maxmem = 2000;

use warnings;
use strict;
$| = 1;
use DBI;
use Cwd;
use Cwd 'abs_path';
use File::Path;
use lib 'scripts';
use shared;

# Check that is run from top level only

my $LIB_DIR = 'libraries';

if (not -d $LIB_DIR )
{
	die "Please run execLoadLibrary.pl from the top level TCW directory only\n";
}

my %Params;  #values from configuration files
our $PAVEcfg = 'LIB.cfg'; 
my $project_name = ''; 

#############################################################
# Get command-line parameters
if (0 == scalar @ARGV || $ARGV[0] =~ /^help$/i) {
	print "\nUsage: execLoadLibrary.pl [-q] <directory> \n";
	print "	<directory> must be under /libraries.\n";
	print "Load the libraries specified in <directory>/LIB.cfg.\n";
	print "Optional -q runs without prompting.\n";
	exit;
}

my $argStart = 0;
if ($ARGV[0] eq "-q") 
{
	$argStart = 1;
}
$project_name = $ARGV[$argStart];

if (1 + $argStart < scalar @ARGV) {
	$PAVEcfg = $ARGV[1 + $argStart];
}


sub listdirs {
	opendir(PRODIR, "$LIB_DIR/");
	my @prosubdirs = grep { /.*/} readdir(PRODIR);
	closedir(PRODIR);
	if (2 < scalar @prosubdirs) {
		print "The following project directories are under the /$LIB_DIR:\n";
		foreach my $sd (sort @prosubdirs) {
			if (-d "$LIB_DIR/$sd") {
				print "   $sd\n" unless($sd eq '.' || $sd eq '..');
			} 
		}
	}
}

$PAVEcfg = "$LIB_DIR/$project_name/$PAVEcfg";
die "Config file $PAVEcfg does not exist.\n" unless -f $PAVEcfg;
my $HOSTScfg = "HOSTS.cfg";

readCfgFile($PAVEcfg,\%Params);
if (not defined $Params{PAVE_db})
{
	die "Config file missing PAVE_db\n";
}
my $PAVE_db = $Params{PAVE_db};

completeDBParams(\%Params,$HOSTScfg);

# PAVE database parameters
my $PAVE_usr = $Params{PAVE_user};
my $PAVE_host = $Params{PAVE_host};
my $PAVE_password = $Params{PAVE_password};
#Make sure PAVE DB is there 
my $dbh = DBI->connect( "dbi:mysql:mysql;host=$PAVE_host", "$PAVE_usr", "$PAVE_password",
		{ PrintError => 0, ChopBlanks => 1, LongReadLen => 100000 } ) 
		or die "*** could not locate MySQL database on $PAVE_host (are the username/password in LIB.cfg correct?).\n";  

my $jardir = "java/jars";
my $jar = "$jardir/stcw.jar";

if (not -f $jar)
{
	die "can't find $jar; make sure to run from the pave_2_0 directory.\n";
}

my $classpath = "$jar:$jardir/mysql-connector-java-5.0.5-bin.jar";
my $cmd = "java -Xmx${maxmem}m -cp $classpath assem.LoadLibMain ".join(" ",@ARGV);

#print "execute:$cmd\n";
system($cmd);

